<?php
namespace app\index\controller;
use app\common\controller\PayBase;
use think\Db;
use app\index\model\ChongzhiList;
class Payxgx extends PayBase
{
    protected $partner;
    protected $key;
    protected $pay_url;
    protected $back_url;
    protected $href_url;

    public function __construct() {
        parent::__construct();
        $this->merchant_id = '82000546';
        $this->key = '5RR6JIALSZSKXSWM';
        $this->pay_url = 'https://www.xgxpay.com/Pay/v2/index';
        $this->back_url = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/index/Payxgx/callBank';
        $this->href_url = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/index/Payxgx/hrefUrl';
    }

    /**
     * 上行支付接口
     */
    public function initPay($username='',$pay_type='',$amount=-1,$from=0)
    {
        //接收数据
        $user = cookie('username','');
        $password = cookie('password','');
        $username =  empty($username) ? input('post.username','') : $username;
        $pay_type = empty($pay_type) ? input('post.pay_type','') : $pay_type;
        $amount = -1==$amount ? input('post.amount',0) : $amount;
        $ctime = time();
        if($pay_type=='null' || $pay_type=='') return packJson('',$pay_type.'请选择支付方式',500);
        $pay_method = Db::name('pay_type_list')
            ->alias("a")
            ->join('__PAY_METHOD__ b','a.method_id=b.id','LEFT')
            ->where(['a.method'=>6,'a.type_value'=>$pay_type])
            ->field('a.type_name,b.name,b.id,b.method,b.money')->find();
        $remark = $pay_method['type_name'].'-'.$pay_method['name'];
        //若为网银支付支付则转换银行编码
        if(!is_numeric($pay_type)) {
            $bank_code = $pay_type;
            $pay_type = '3';
        }
        //验证用户信息
        if( 0==$from ){
            if(!$user || !$username || ($user!=$username)) return packJson('','用户身份验证失败',500);
            $user_info = Db::name('username')->field('id,us_class,swzh,nbzh')->where(['username'=>$username,'password'=>$password])->find();
        }else{
            $user_info = Db::name('username')->field('id,us_class,swzh,nbzh')->where(['username'=>$username])->find();
        }
        if(!$user_info) return packJson('','用户身份验证失败',500);
        if($user_info['swzh'] == 1) return packJson('','试玩账号无法充值',500);
        if($user_info['nbzh'] == 1) return packJson('','内部账号不支持线上充值',500);

        //充值防骚扰是否开启，并进行处理
        $harassment = Db::name('xt_czfsr')->find();
        if($harassment['open'] > 0) {
            $nowys = $ctime - $harassment['time_xs'] * 60;
            $old_czjl = Db::name('chongzhi_list')->where('username',$username)->where('cztime','>',$nowys)->find();
            if($old_czjl['id'] > 0) {
                return packJson('',"系统充值防骚扰已开启，{$harassment['time_xs']}分钟内只能充值1次！",500);
            }
        }

        //验证金额
        if($amount <= 0) return packJson('','请输入充值金额',500);
        if($amount < 10) return packJson('','最低充值金额为十元人民币',500);
        if($amount > 5000) return packJson('','充值金额超过范围',500);

        //计算优惠金额
        $msje = $msbs = 0;
        $cz_set = Db::name('xt_chongzhi')->find();
        $user_class = Db::name('us_class')->where('id',$user_info['us_class'])->find();
        $zsje = $amount * $user_class['czzsbl'] / 100;
        $zsbs = $user_class['czzsbl'];
        if($amount >= $cz_set['xscz_je']) {
            $msje = $amount * $cz_set['xscz_zs'] / 100;
            $msbs = $cz_set['xscz_zs'];
        }
        //充值方案赠送
        $method_money = 0.00;
        if( floatval( $pay_method['money'] ) > 0 ){
            if( 0==intval( $pay_method['method'] ) ){
                //金额
                $method_money = $pay_method['money'];
            }else{
                //比例
                $method_money = floatval($amount) * floatval($pay_method['money']) / 100;
            }
        }
        $method_money = sprintf("%.2f",substr(sprintf("%.3f", $method_money), 0, -2));

        //生成订单号
        $order_sn = 'XGX' . str_pad($user_info['id'],5,'0',STR_PAD_LEFT) . $ctime . rand(111,999);
        //组装数据
        if( 1==$from ) $this->href_url.="Third";
        $data = array();
        $data['merchant_id'] = $this->merchant_id;
        $data['payment_way'] = $pay_type;
        $data['order_amount'] = $amount;
        $data['source_order_id'] = $order_sn;
        $data['goods_name'] = '新干线在线充值';
        if($pay_type == '3') $data['bank_code'] = $bank_code;
        $data['client_ip'] = get_ip();
        $data['notify_url'] = $this->back_url;
        $data['return_url'] = $this->href_url;
        $data['sign'] = $this->signature($this->key,$data);
        $ret = $this->curl_post_https($this->pay_url,$data);
        $result = json_decode($ret,true);
        if( 1==intval($result['rec_code']) ){
        	$u = Db::name('username')->where('username',$username)->value('je');
            $model = new ChongzhiList();
            if( $model->setTransRechargeInfo($order_sn,$amount,$username,0,0,1,$remark,$ctime,'新干线线上支付','系统自动',get_ip(),0,$pay_type,$zsje,$zsbs,$msje,$msbs,$user_info['us_class'],'',0,$method_money,$u) ){
                return packJson($result['pay_url'],'',200);
            }else{
                return packJson('',"订单生产错误",500);
            }
        }else{
            return packJson('',$result['msg'],500);
        }
    }

    private function checkSign($key='',$params=[])
    {
        if(!array_key_exists('sign',$params)) {
            return false;
        }

        $sign = $params['sign'];
        if(empty($sign)) {
            return false;
        }

        unset($params['sign']);
        $correct_sign = $this->bulidSign($key,$params);

        return $sign==$correct_sign;
    }
    /**
     * 计算参数签名
     * @param string $key
     * @param array $params
     * @return string
     */
    function signature($key='',$params=[]){

        $params['token']=$key; //加入token
        ksort($params); //参数数组按键升序排列
        $clear_text='';    //将参数值按顺序拼接成字符串
        foreach ($params as $key=>$value){
            $clear_text .= $key.'='.$value.'&';
        }
        $clear_text = trim($clear_text,'&');
        $cipher_text=md5($clear_text); //计算md5 hash
        return $cipher_text;
    }

    /**
     * 回调跳转接口
     */
    public function hrefUrl(){
    }
    public function hrefUrlThird(){
    }
    /**
     * 回调通知接口
     */
    public function callBank(){
    }
    function curl_post_https($url,$data){ // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }
}